package com.eqdd.yiqidian.ui;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.SparseArray;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.eqdd.annotation.datasave.DealCodeClass;
import com.eqdd.yiqidian.MainActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseApplication;
import com.eqdd.yiqidian.base.CodeRule;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.fragment.FaxianFragment;
import com.eqdd.yiqidian.fragment.FunctionFragment;
import com.eqdd.yiqidian.fragment.MineFragment;
import com.eqdd.yiqidian.fragment.TongxunluFragment;
import com.eqdd.yiqidian.fragment.XiaoxiFragment;
import com.eqdd.yiqidian.rxbus2.Subscribe;
import com.eqdd.yiqidian.rxbus2.ThreadMode;
import com.eqdd.yiqidian.ui.yiqiyue.YueMainActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.gamerole.floatactionmenulib.RapidFloatingActionButton;
import com.gamerole.floatactionmenulib.RapidFloatingActionHelper;
import com.gamerole.floatactionmenulib.RapidFloatingActionLayout;
import com.gamerole.floatactionmenulib.contentimpl.labellist.RFACLabelItem;
import com.gamerole.floatactionmenulib.contentimpl.labellist.RapidFloatingActionContentLabelList;
import com.gamerole.floatactionmenulib.util.ABShape;
import com.gamerole.floatactionmenulib.util.ABTextUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.roughike.bottombar.BottomBarTab;
import com.tbruyelle.rxpermissions.RxPermissions;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import me.leolin.shortcutbadger.ShortcutBadger;

public class MainActivity extends BaseActivity implements RongIM.UserInfoProvider, IUnReadMessageObserver
        , RapidFloatingActionContentLabelList.OnRapidFloatingActionContentLabelListListener {


    private SparseArray<Class> menuArray = new SparseArray();
    private static final int REQUEST_CODE = 1;
    private MainActivityCustom dataBinding;
    private User user;
    private String fragment1Tag = "消息";
    private String fragment2Tag = "通讯录";
    private String fragment3Tag = "功能";
    private String fragment4Tag = "发现";
    private String fragment5Tag = "我的";
    private BottomBarTab xiaoxi;
    private ActionSheetDialog bottomChoose;
    private BottomBarTab tongxunlu;
    private BottomBarTab faxian;
    private BottomBarTab mine;
    private BottomBarTab function;
    private RapidFloatingActionHelper rfabHelper;

    @DealCodeClass(classes = {TongxunluFragment.class})
    public void updateFriendApplyNum(int num) {
        if (num > 0) {
            tongxunlu.setBadgeCount(num);
        } else {
            tongxunlu.removeBadge();
        }
    }

    @DealCodeClass(classes = {MineFragment.class})
    public void updateMineNum(int num) {
        if (num > 0) {
            mine.setBadgeCount(num);
        } else {
            mine.removeBadge();
        }
    }

    @DealCodeClass(classes = {FaxianFragment.class})
    public void updateFaxian(int num) {
        if (num > 0) {
            faxian.setBadgeCount(num);
        } else {
            faxian.removeBadge();
        }
    }

    @DealCodeClass(classes = {FunctionFragment.class})
    public void updateGongneng(int num) {
        if (num > 0) {
            function.setBadgeCount(num);
        } else {
            function.removeBadge();
        }
    }

    @Subscribe(code = CodeRule.USER_INFO, threadMode = ThreadMode.MAIN)
    public void updateUser() {
        user = GreenDaoUtil.getUser();
    }


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    }

    @Override
    public void initData() {
        isDealCode = true;
        isRxbus = true;
        user = GreenDaoUtil.getUser();
        menuArray.put(0, YueMainActivity.class);
        initRong();
        initBottomBar();
        initChooseDialog();
        initSlideUpMenu();
    }

    private void initSlideUpMenu() {
        RapidFloatingActionContentLabelList rfaContent = new RapidFloatingActionContentLabelList(this);
        rfaContent.setOnRapidFloatingActionContentLabelListListener(this);
        List<RFACLabelItem> items = new ArrayList<>();
        items.add(new RFACLabelItem<Integer>()
                .setLabel("易企阅")
                .setResId(R.mipmap.ic_launcher)
                .setIconNormalColor(0xffd84315)
                .setIconPressedColor(0xffbf360c)
                .setWrapper(0)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("tiantian.china.2@gmail.com")
                .setResId(R.mipmap.ic_launcher)
                .setIconNormalColor(0xff4e342e)
                .setIconPressedColor(0xff3e2723)
                .setLabelColor(Color.WHITE)
                .setLabelSizeSp(14)
                .setLabelBackgroundDrawable(ABShape.generateCornerShapeDrawable(0xaa000000, ABTextUtil.dip2px(this, 4)))
                .setWrapper(1)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("WangJie")
                .setResId(R.mipmap.ic_launcher)
                .setIconNormalColor(0xff056f00)
                .setIconPressedColor(0xff0d5302)
                .setLabelColor(0xff056f00)
                .setWrapper(2)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("Compose")
                .setResId(R.mipmap.ic_launcher)
                .setIconNormalColor(0xff283593)
                .setIconPressedColor(0xff1a237e)
                .setLabelColor(0xff283593)
                .setWrapper(3)
        );
        rfaContent
                .setItems(items)
                .setIconShadowRadius(ABTextUtil.dip2px(this, 5))
                .setIconShadowColor(0xff888888)
                .setIconShadowDy(ABTextUtil.dip2px(this, 5))
        ;
        rfabHelper = new RapidFloatingActionHelper(
                this,
                dataBinding.activityMainRfal,
                dataBinding.activityMainRfab,
                rfaContent
        ).build();
    }

    @Override
    public void onRFACItemLabelClick(int position, RFACLabelItem item) {
        rfabHelper.toggleContent();
        dealMenu(position);
    }

    private void dealMenu(int position) {
        startActivity(menuArray.get(position));
    }

    @Override
    public void onRFACItemIconClick(int position, RFACLabelItem item) {
        rfabHelper.toggleContent();
        dealMenu(position);
    }

    @Override
    public void setView() {
        RxView.clicks(dataBinding.includeTitle.ivSearch)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> startActivity(SearchActivity.class));


    }

    @Override
    public void lastRun() {
        if (register != null) {
            ((MainActivity$$DealCodeInjector) register).update1();
            ((MainActivity$$DealCodeInjector) register).update2();
            ((MainActivity$$DealCodeInjector) register).update3();
            ((MainActivity$$DealCodeInjector) register).update4();
        }
    }

    private void initBottomBar() {
        mine = dataBinding.bottomBar.getTabWithId(R.id.tab_my);
        xiaoxi = dataBinding.bottomBar.getTabWithId(R.id.tab_xiaoxi);
        tongxunlu = dataBinding.bottomBar.getTabWithId(R.id.tab_tongxunlu);
        faxian = dataBinding.bottomBar.getTabWithId(R.id.tab_faxian);
        function = dataBinding.bottomBar.getTabWithId(R.id.tab_function);
        dataBinding.bottomBar.setDefaultTab(R.id.tab_function);
        dataBinding.bottomBar.setOnTabSelectListener((tabId) -> onChecked(tabId));
    }

    public void onChecked(int checkedId) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment fragment1 = fm.findFragmentByTag(fragment1Tag);
        Fragment fragment2 = fm.findFragmentByTag(fragment2Tag);
        Fragment fragment3 = fm.findFragmentByTag(fragment3Tag);
        Fragment fragment4 = fm.findFragmentByTag(fragment4Tag);
        Fragment fragment5 = fm.findFragmentByTag(fragment5Tag);
        if (fragment1 != null) {
            ft.hide(fragment1);
        }
        if (fragment2 != null) {
            ft.hide(fragment2);
        }
        if (fragment3 != null) {
            ft.hide(fragment3);
        }
        if (fragment4 != null) {
            ft.hide(fragment4);
        }
        if (fragment5 != null) {
            ft.hide(fragment5);
        }
        switch (checkedId) {
            case R.id.tab_xiaoxi:
                if (fragment1 == null) {
                    fragment1 = new XiaoxiFragment();
                    ft.add(R.id.contentContainer, fragment1, fragment1Tag);
                } else {
                    ft.show(fragment1);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("消息");
                findViewById(R.id.iv_search).setVisibility(View.VISIBLE);
                break;
            case R.id.tab_tongxunlu:
                if (fragment2 == null) {
                    fragment2 = new TongxunluFragment();
                    ft.add(R.id.contentContainer, fragment2, fragment2Tag);
                } else {
                    ft.show(fragment2);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("通讯录");
                findViewById(R.id.iv_search).setVisibility(View.GONE);


                break;
            case R.id.tab_function:
                if (fragment3 == null) {
                    fragment3 = new FunctionFragment();
                    ft.add(R.id.contentContainer, fragment3, fragment3Tag);
                } else {
                    ft.show(fragment3);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("易企点工业互联网平台");
                findViewById(R.id.iv_search).setVisibility(View.GONE);


                break;
            case R.id.tab_faxian:
                if (fragment4 == null) {
                    fragment4 = new FaxianFragment();
                    ft.add(R.id.contentContainer, fragment4, fragment4Tag);
                } else {
                    ft.show(fragment4);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("发现");
                findViewById(R.id.iv_search).setVisibility(View.GONE);


                break;
            case R.id.tab_my:
                if (fragment5 == null) {
                    fragment5 = new MineFragment();
                    ft.add(R.id.contentContainer, fragment5, fragment5Tag);
                } else {
                    ft.show(fragment5);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("我的");
                findViewById(R.id.iv_search).setVisibility(View.GONE);

                break;
            default:
                break;
        }
        ft.commit();
    }

    private void initRong() {
        RongIM.setUserInfoProvider(this, true);
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };
        System.out.println("更新融云数据");
        RongIM.getInstance().setMessageAttachedUserInfo(true);

        /**
         * 刷新用户缓存数据。
         *
         * @param userInfo 需要更新的用户缓存数据。
         */
        RongIM.getInstance().setCurrentUserInfo(new UserInfo(user.getGuid(), user.getPname(), Uri.parse(user.getIphoto())));
        RongIM.getInstance().refreshUserInfoCache(new UserInfo(user.getGuid(), user.getPname(), Uri.parse(user.getIphoto())));
        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);
    }


    private void initChooseDialog() {
        bottomChoose = ChooseAlertView.getBottomChoose(this, null, new String[]{"扫一扫"}, (o, position) -> {
            RxPermissions.getInstance(this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.RECORD_AUDIO)
                    .subscribe(granted -> {
                        // 当R.id.enableCamera被点击的时候触发获取权限
                        if (granted) {
                            System.out.println("已授权");
                            Intent intent = new Intent(MainActivity.this, ScanZXingActivity.class);
                            startActivityForResult(intent, REQUEST_CODE);
                        } else {
                            ToastUtil.showLong("请在设置中开启照相权限");
                        }
                    });
        });
    }

    @Override
    public UserInfo getUserInfo(String s) {
        return new UserInfo(user.getGuid(), user.getPname(),
                Uri.parse(user.getIphoto()));//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
    }

    @Override
    public void onCountChanged(int i) {
//        startService(new Intent(MainActivity.this, RongyunService.class));
        System.out.println("未读消息树" + i);
        if (i <= 0) {
            xiaoxi.removeBadge();
            ShortcutBadger.removeCount(BaseApplication.getApplication());
        } else {
            xiaoxi.setBadgeCount(i);
            ShortcutBadger.applyCount(BaseApplication.getApplication(), i);

        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_add:
                bottomChoose.show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(this);
        super.onDestroy();
    }

}
